package org.dromara.datacheck.service.impl.jst;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.datacheck.domain.bo.JstAndJDTableDataEntryBo;
import org.dromara.datacheck.domain.bo.jst.ConsignmentBusinessDifferenceBo;
import org.dromara.datacheck.domain.bo.jst.JstAllotEnterOrderBo;
import org.dromara.datacheck.domain.jd.JdDirectTransferOrder;
import org.dromara.datacheck.domain.jst.JstAllotEnterOrder;
import org.dromara.datacheck.domain.vo.jd.JdDirectTransferOrderVo;
import org.dromara.datacheck.domain.vo.jst.JstAllotEnterOrderVo;
import org.dromara.datacheck.mapper.jd.JdDirectTransferOrderMapper;
import org.dromara.datacheck.mapper.jst.JstAllotEnterOrderMapper;
import org.dromara.datacheck.service.jst.IJstAllotEnterOrderService;
import org.dromara.datacheck.util.MyUtil;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 聚水潭-调拨入单Service业务层处理
 *
 * @author 刘武贵
 * @date 2024-09-08
 */
@RequiredArgsConstructor
@Service
public class JstAllotEnterOrderServiceImpl implements IJstAllotEnterOrderService {

    private final JstAllotEnterOrderMapper baseMapper;

    @Resource
    private JdDirectTransferOrderMapper jdDirectTransferOrderMapper;

    /**
     * 查询聚水潭-调拨入单
     *
     * @param id 主键
     * @return 聚水潭-调拨入单
     */
    @Override
    public JstAllotEnterOrderVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询聚水潭-调拨入单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 聚水潭-调拨入单分页列表
     */
    @Override
    public TableDataInfo<JstAllotEnterOrderVo> queryPageList(JstAllotEnterOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = buildQueryWrapper(bo);
        Page<JstAllotEnterOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的聚水潭-调拨入单列表
     *
     * @param bo 查询条件
     * @return 聚水潭-调拨入单列表
     */
    @Override
    public List<JstAllotEnterOrderVo> queryList(JstAllotEnterOrderBo bo) {
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<JstAllotEnterOrder> buildQueryWrapper(JstAllotEnterOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterNumber()), JstAllotEnterOrder::getAllotEnterNumber, bo.getAllotEnterNumber());
        lqw.eq(bo.getAllotOutNumber() != null, JstAllotEnterOrder::getAllotOutNumber, bo.getAllotOutNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getAllotType()), JstAllotEnterOrder::getAllotType, bo.getAllotType());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptDate()), JstAllotEnterOrder::getReceiptDate, bo.getReceiptDate());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreateDate()), JstAllotEnterOrder::getReceiptCreateDate, bo.getReceiptCreateDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCalloutWarehouse()), JstAllotEnterOrder::getCalloutWarehouse, bo.getCalloutWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getFoldWarehouse()), JstAllotEnterOrder::getFoldWarehouse, bo.getFoldWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreator()), JstAllotEnterOrder::getReceiptCreator, bo.getReceiptCreator());
        lqw.eq(StringUtils.isNotBlank(bo.getProductNumber()), JstAllotEnterOrder::getProductNumber, bo.getProductNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStyleNumber()), JstAllotEnterOrder::getStyleNumber, bo.getStyleNumber());
        lqw.like(StringUtils.isNotBlank(bo.getShopName()), JstAllotEnterOrder::getShopName, bo.getShopName());
        lqw.eq(bo.getQuantity() != null, JstAllotEnterOrder::getQuantity, bo.getQuantity());
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterOrderRemark()), JstAllotEnterOrder::getAllotEnterOrderRemark, bo.getAllotEnterOrderRemark());
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(JstAllotEnterOrder::getNewOrderDate,
                params.get("beginTime"),
                params.get("endTime"));
        }
        return lqw;
    }

    /**
     * 新增聚水潭-调拨入单
     *
     * @param bo 聚水潭-调拨入单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(JstAllotEnterOrderBo bo) {
        JstAllotEnterOrder add = MapstructUtils.convert(bo, JstAllotEnterOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改聚水潭-调拨入单
     *
     * @param bo 聚水潭-调拨入单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(JstAllotEnterOrderBo bo) {
        JstAllotEnterOrder update = MapstructUtils.convert(bo, JstAllotEnterOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(JstAllotEnterOrder entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除聚水潭-调拨入单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 查询聚水潭-调拨入单列表所有数据
     *
     * @return 聚水潭-调拨入单列表
     */
    @Override
    public List<JstAllotEnterOrder> queryAll() {
        return baseMapper.selectList(null);
    }

    /**
     * 清空聚水潭-调拨入单列表所有数据
     *
     * @return 聚水潭-调拨入单列表
     */
    @Override
    public Integer deleteAll() {
        return baseMapper.delete(new QueryWrapper<>());
    }

    /**
     * 查询聚水潭-调拨单列表以及金蝶-直接调拨单数据汇总（按日期汇总）
     * 场景分类：8、调拨-仓库间调拨
     */
    @Override
    public TableDataInfo<JstAndJDTableDataEntryBo> jstAndJdSumByDateByTransferBetweenWarehouses() {
        List<JstAndJDTableDataEntryBo> jstAndJDTableDataEntryList =new ArrayList<>();
        JstAndJDTableDataEntryBo jstAndJDTableDataEntry = new JstAndJDTableDataEntryBo();
        // 1、查询两个平台数据
        // 1-1、查询聚水潭的数据
        LambdaQueryWrapper<JstAllotEnterOrder> lqw1 = Wrappers.lambdaQuery();
        lqw1.eq(JstAllotEnterOrder::getDataSign, "0");
        List<JstAllotEnterOrderVo> jstAllotEnterOrderList = baseMapper.selectVoList(lqw1);

        // 1-2、查询金蝶的数据
        LambdaQueryWrapper<JdDirectTransferOrder> lqw2 = Wrappers.lambdaQuery();
        lqw2.eq(JdDirectTransferOrder::getCalloutWarehouse, "销退仓");
        lqw2.eq(JdDirectTransferOrder::getFoldWarehouse, "东莞仓");
        List<JdDirectTransferOrderVo> jdDirectTransferOrderList = jdDirectTransferOrderMapper.selectVoList(lqw2);

        // 2、生成日期列表和处理日期
        // 2-1、生成日期列表，以聚水潭的最晚日期为截止日期取
        List<Date> dateList = jdDirectTransferOrderList.stream()
            .sorted(Comparator.comparing(JdDirectTransferOrderVo::getNewOrderDate))
            .map(JdDirectTransferOrderVo::getNewOrderDate)
            .distinct()
            .collect(Collectors.toList());

        // 2-2、将日期列表转换为字符串列表
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        List<String> dateStringList = dateList.stream()
            .map(date -> dateFormat.format(date))
            .collect(Collectors.toList());

        // 2-3、获取去重后的日期列表，并转换格式
        Set<String> formattedDateSet = dateStringList.stream()
            // 将字符串转换为 LocalDate 对象
            .map(MyUtil::parseToLocalDate)
            .sorted()
            .map(MyUtil::formatDateStringByLocalDate)
            .collect(Collectors.toSet());
        List<String> formattedDateList = new ArrayList<>(formattedDateSet);
        Collections.sort(formattedDateList, Comparator.naturalOrder());

        // 3、处理两个平台的日期
        // 3-1、处理聚水潭和金蝶的数据里面的日期
        // key 为日期，value 为数量
        Map<String, Integer> jstCountMap = jstAllotEnterOrderList.stream()
            .filter(order -> order.getNewOrderDate() != null)
            .sorted(Comparator.comparing(JstAllotEnterOrderVo::getNewOrderDate))
            .collect(Collectors.groupingBy(
                order -> MyUtil.formatDateStringNoPadZero(dateFormat.format(order.getNewOrderDate())),
                Collectors.summingInt(JstAllotEnterOrderVo::getQuantity)
            ));

        // 3-2、处理金蝶的数据里面的日期
        // key 为日期，value 为数量
        Map<String, Integer> jdCountMap = jdDirectTransferOrderList.stream()
            .filter(order -> order.getReceiptDate() != null)
            .sorted(Comparator.comparing(JdDirectTransferOrderVo::getReceiptDate))
            .collect(Collectors.groupingBy(
                order -> MyUtil.formatDateStringPadZero(order.getReceiptDate()),
                Collectors.summingInt(JdDirectTransferOrderVo::getAllotQuantity)
            ));

        // 4、构建形如<date1,日期>的key value对，这个是前端要求
        Map<String, String> dateMap = MyUtil.buildDateMap(formattedDateList);

        // 5、构建表格数据
        // 数据格式形如: "tableList": [
        //                {
        //                    "label": "金蝶",
        //                    "date1": 0,
        //                    "date2": 2,
        //                    "date3": 3420,
        //                    "date4": 179,
        //                    "date5": 449,
        //                    "date6": 922,
        //                    "date7": 0,
        //                    "date8": 1822,
        //                    "date9": 0
        //                },
        //                {
        //                    "label": "聚水潭",
        //                    "date1": 2130,
        //                    "date2": 2,
        //                    "date3": 3420,
        //                    "date4": 179,
        //                    "date5": 449,
        //                    "date6": 922,
        //                    "date7": 1409,
        //                    "date8": 1822,
        //                    "date9": 1631
        //                },
        //                {
        //                    "label": "差异",
        //                    "date1": 2130,
        //                    "date2": 0,
        //                    "date3": 0,
        //                    "date4": 0,
        //                    "date5": 0,
        //                    "date6": 0,
        //                    "date7": 1409,
        //                    "date8": 0,
        //                    "date9": 1631
        //                }
        //            ]
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 5-1、初始化三个 Map 来存储数据
        Map<String, Object> jdData = new LinkedHashMap<>();
        Map<String, Object> jstData = new LinkedHashMap<>();
        Map<String, Object> diffData = new LinkedHashMap<>();

        // 设置 label
        jdData.put("label", "金蝶");
        jstData.put("label", "聚水潭");
        diffData.put("label", "差异");

        // 5-2、遍历日期列表，填充数据
        int dateIndex = 1;
        for (String date : formattedDateList) {
            int jstCount = jstCountMap.getOrDefault(date, 0);
            int jdCount = jdCountMap.getOrDefault(date, 0);
            int diff = Math.abs(jstCount - jdCount);

            // 填充数据
            jdData.put("date" + dateIndex, jdCount);
            jstData.put("date" + dateIndex, jstCount);
            diffData.put("date" + dateIndex, diff);

            dateIndex++;
        }

        // 5-3、将三个 Map 添加到结果列表中
        resultList.add(jdData);
        resultList.add(jstData);
        resultList.add(diffData);
        // 5-4、设置表格数据
        jstAndJDTableDataEntry.setTableList(resultList);

        // 6、构建列数据
        // 数据格式形如:
        // [
        //                {
        //                    "label": "系统",
        //                    "prop": "label"
        //                },
        //                {
        //                    "label": "2024年07月31日",
        //                    "prop": "date1"
        //                },
        // ]
        List<Map<String, Object>> columnList = new ArrayList<>();
        // 6-1、添加 "系统" 列
        Map<String, Object> systemColumn = new LinkedHashMap<>();
        systemColumn.put("label", "系统");
        systemColumn.put("prop", "label");
        columnList.add(systemColumn);

        // 6-2、添加日期列
        for (int i = 0; i <formattedDateList.size() +1; i++) {
            Map<String, Object> dateColumn = new LinkedHashMap<>();
            // 可以根据需要修改日期格式，根据业务需要，这里先按照date1这样处理
            dateColumn.put("label", dateMap.get("date" + i));
            dateColumn.put("prop", "date" + i);
            columnList.add(dateColumn);
            dateIndex++;
        }
        // 6-3、设置表格数据
        jstAndJDTableDataEntry.setColumnList(columnList);
        jstAndJDTableDataEntryList.add(jstAndJDTableDataEntry);

        // 7、构建JSON，构建返回数据
        TableDataInfo<JstAndJDTableDataEntryBo> result = new TableDataInfo<>();
        result.setRows(jstAndJDTableDataEntryList);
        result.setMsg("查询成功");

        return result;
    }

    /**
     * 查询聚水潭-调拨单列表（金蝶缺少的数据）
     * 场景分类：8、调拨-仓库间调拨
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<JstAllotEnterOrderVo> queryPageListByTransferBetweenWarehousesByJdDeficiency1(JstAllotEnterOrderBo bo, PageQuery pageQuery) {
        // 计算8、调拨-仓库间调拨场景业务差异数据
        ConsignmentBusinessDifferenceBo consignmentBusinessDifferenceBo = this.calculateTransferBetweenWarehousesBusinessDifference();
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = buildQueryWrapperByTransferBetweenWarehousesByJdDeficiency(bo, consignmentBusinessDifferenceBo);
        Page<JstAllotEnterOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    /**
     * 计算8、调拨-仓库间调拨场景业务差异数据
     */
    private ConsignmentBusinessDifferenceBo calculateTransferBetweenWarehousesBusinessDifference() {
        ConsignmentBusinessDifferenceBo consignmentBusinessDifferenceBo = new ConsignmentBusinessDifferenceBo();
        // List<Map<key调入单号 value物料编码>>集合，最终组成要去查询金蝶缺少数据的条件
        List<Map<String, List<String>>> orderMaterialMap = new ArrayList<>();
        // key调入单号 value聚水潭调拨单集合
        Map<String, List<JstAllotEnterOrderVo>> groupedByInnerOrderNumber1 = new HashMap<>();
        // key调入单号 value聚水潭调拨单对应的物料编码集合
        Map<String, List<String>> groupedByInnerOrderNumber2 = new HashMap<>();
        // key是单据编号， value是该单据编号对应的金蝶直接调拨单集合
        Map<String, List<JdDirectTransferOrderVo>> groupedByReceiptNumber1 = new HashMap<>();
        // key是单据编号， value是该单据编号对应的金蝶直接调拨单的物料编码集合
        Map<String, List<String>> groupedByReceiptNumber2 = new HashMap<>();
        // 聚水潭日期
        Set<String> jstOrderDateList = new HashSet<>();

        // 1、查询聚水潭调拨单，并且按照调入单号分组
        // 一个调入单号对应多条聚水潭调拨单。形如<String,List<JstSaleOutWarehouseOrder>>，key是调入单号， value是该调入单号对应的聚水潭调拨单集合
        LambdaQueryWrapper<JstAllotEnterOrder> lqw1 = Wrappers.lambdaQuery();
        lqw1.eq(JstAllotEnterOrder::getDataSign, "0");
        List<JstAllotEnterOrderVo> jstAllotEnterOrderList = baseMapper.selectVoList(lqw1);
        if (CollUtil.isNotEmpty(jstAllotEnterOrderList)) {
            // 根据 allotEnterNumber 分组
            groupedByInnerOrderNumber1 = jstAllotEnterOrderList.stream()
                .collect(Collectors.groupingBy(JstAllotEnterOrderVo::getAllotEnterNumber));

            // 第二次分组，形如Map<String,List<String>>，key是调入单号， value是该调入单号对应的聚水潭调拨单物料编码集合
            // 根据 allotEnterNumber 分组，并提取 jdMaterialCode
            groupedByInnerOrderNumber2 = jstAllotEnterOrderList.stream()
                .collect(Collectors.groupingBy(
                    JstAllotEnterOrderVo::getAllotEnterNumber,
                    Collectors.mapping(JstAllotEnterOrderVo::getJdMaterialCode, Collectors.toList())
                ));

        }

        // 2、查询金蝶直接调拨单，并且按照单据编号分组
        LambdaQueryWrapper<JdDirectTransferOrder> lqw2 = Wrappers.lambdaQuery();
        lqw2.eq(JdDirectTransferOrder::getCalloutWarehouse, "销退仓");
        lqw2.eq(JdDirectTransferOrder::getFoldWarehouse, "东莞仓");
        List<JdDirectTransferOrderVo> jdDirectTransferOrderList = jdDirectTransferOrderMapper.selectVoList(lqw2);
        if (CollUtil.isNotEmpty(jdDirectTransferOrderList)) {
            // 单据编号形如2057362-001-JS的，需要把-001这部分内容去掉，一个调入单号对应多条金蝶直接调拨单
            // 形如<String,List<JdDirectTransferOrder>>，key是单据编号， value是该单据编号对应的金蝶直接调拨单集合
            groupedByReceiptNumber1 = jdDirectTransferOrderList.stream()
                .collect(Collectors.groupingBy(order -> {
                    String receiptNumber = order.getReceiptNumber();
                    if (receiptNumber != null && receiptNumber.contains("-")) {
                        return receiptNumber.split("-")[0];
                    }
                    return receiptNumber;
                }));
            // 第二次分组，形如Map<String,List<String>>，key是单据编号， value是该单据编号对应的金蝶直接调拨单物料编码集合
            groupedByReceiptNumber2 = jdDirectTransferOrderList.stream()
                .collect(Collectors.groupingBy(order -> {
                        String receiptNumber = order.getReceiptNumber();
                        if (receiptNumber != null && receiptNumber.contains("-")) {
                            return receiptNumber.split("-")[0];
                        }
                        return receiptNumber;
                    },
                    Collectors.mapping(JdDirectTransferOrderVo::getMaterialCode, Collectors.toList())));

        }

        if (CollUtil.isNotEmpty(groupedByInnerOrderNumber2) && CollUtil.isNotEmpty(groupedByReceiptNumber2)) {
            // 3、数据比较，两次比较均以聚水潭的为准，比对出缺少的数据，组装多个Map<String, List<String>，添加进List<Map<String, List<String>>> orderMaterialMap中
            // 3-1、第一次比较，比较出金蝶不存在的调入单号，其对应的物料编码需要去第1步中的聚水潭分组数据查询，组装多个Map<String, List<String>
            // 最后添加进List<Map<String, List<String>>> orderMaterialMap中
            Set<String> jstAllotEnterNumbers = groupedByInnerOrderNumber1.keySet();
            Set<String> jdReceiptNumbers = groupedByReceiptNumber1.keySet();

            // 金蝶中不存在的调入单号
            Set<String> missingInnerOrderNumbers = jstAllotEnterNumbers.stream()
                .filter(allotEnterNumber -> !jdReceiptNumbers.contains(allotEnterNumber))
                .collect(Collectors.toSet());

            for (String missingInnerOrderNumber : missingInnerOrderNumbers) {
                List<String> materialCodes = groupedByInnerOrderNumber2.get(missingInnerOrderNumber);
                if (materialCodes != null) {
                    Map<String, List<String>> missingOrderMaterialMap = new HashMap<>();
                    missingOrderMaterialMap.put(missingInnerOrderNumber, materialCodes);
                    orderMaterialMap.add(missingOrderMaterialMap);
                }
            }

            // 3-2、第二次比较，调入单号相同的情况下，比对缺少的物料编码，组装多个Map<String, List<String>>
            // 最后添加进List<Map<String, List<String>>> orderMaterialMap中
            for (String innerOrderNumber : jstAllotEnterNumbers) {
                if (jdReceiptNumbers.contains(innerOrderNumber)) {
                    List<String> jstMaterialCodes = groupedByInnerOrderNumber2.get(innerOrderNumber);
                    List<String> jdMaterialCodes = groupedByReceiptNumber2.get(innerOrderNumber);

                    if (jstMaterialCodes != null && jdMaterialCodes != null) {
                        // 获取聚水潭和金蝶的日期
                        List<String> jstOrderDates = groupedByInnerOrderNumber1.get(innerOrderNumber).stream()
                            .map(JstAllotEnterOrderVo::getCompareDateToJd)
                            .distinct()
                            .collect(Collectors.toList());
                        List<String> jdOrderDates = groupedByReceiptNumber1.get(innerOrderNumber).stream()
                            .map(JdDirectTransferOrderVo::getReceiptDate)
                            .distinct()
                            .collect(Collectors.toList());

                        // 比较日期
                        for (String jstOrderDate : jstOrderDates) {
                            if (!jdOrderDates.contains(jstOrderDate)) {
                                // 金蝶中不存在该日期的调入单号
                                Map<String, List<String>> missingOrderMaterialMap = new HashMap<>();
                                missingOrderMaterialMap.put(innerOrderNumber, jstMaterialCodes);
                                jstOrderDateList.add(jstOrderDate);
                                orderMaterialMap.add(missingOrderMaterialMap);
                            } else {
                                // 日期相同的情况下，比对缺少的物料编码
                                List<String> jstMaterialCodesForDate = groupedByInnerOrderNumber1.get(innerOrderNumber).stream()
                                    .filter(order -> order.getCompareDateToJd().equals(jstOrderDate))
                                    .map(JstAllotEnterOrderVo::getJdMaterialCode)
                                    .collect(Collectors.toList());
                                List<String> jdMaterialCodesForDate = groupedByReceiptNumber1.get(innerOrderNumber).stream()
                                    .filter(order -> order.getReceiptDate().equals(jstOrderDate))
                                    .map(JdDirectTransferOrderVo::getMaterialCode)
                                    .collect(Collectors.toList());

                                List<String> missingMaterialCodes = jstMaterialCodesForDate.stream()
                                    .filter(materialCode -> !jdMaterialCodesForDate.contains(materialCode))
                                    .collect(Collectors.toList());

                                if (!missingMaterialCodes.isEmpty()) {
                                    Map<String, List<String>> missingOrderMaterialMap = new HashMap<>();
                                    missingOrderMaterialMap.put(innerOrderNumber, missingMaterialCodes);
                                    orderMaterialMap.add(missingOrderMaterialMap);
                                }
                                jstOrderDateList.add(jstOrderDate);
                            }
                        }
                    }
                }
            }
        }
        consignmentBusinessDifferenceBo.setOrderMaterialMap(orderMaterialMap);
        consignmentBusinessDifferenceBo.setJstOrderDateList(jstOrderDateList);
        return consignmentBusinessDifferenceBo;
    }

    /**
     * 构建查询包装器（金蝶缺少的数据）
     * 场景分类：8、调拨-仓库间调拨
     *
     * @param bo                              业务对象，包含查询参数
     * @param consignmentBusinessDifferenceBo 计算业务差异bo对象
     * @return LambdaQueryWrapper 查询包装器，用于后续的条件查询
     */
    private LambdaQueryWrapper<JstAllotEnterOrder> buildQueryWrapperByTransferBetweenWarehousesByJdDeficiency(JstAllotEnterOrderBo bo, ConsignmentBusinessDifferenceBo consignmentBusinessDifferenceBo) {
        // 检测bo的参数
        Boolean boParams = isAnyFieldNonEmpty(bo);
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterNumber()), JstAllotEnterOrder::getAllotEnterNumber, bo.getAllotEnterNumber());
        lqw.eq(bo.getAllotOutNumber() != null, JstAllotEnterOrder::getAllotOutNumber, bo.getAllotOutNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getAllotType()), JstAllotEnterOrder::getAllotType, bo.getAllotType());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptDate()), JstAllotEnterOrder::getReceiptDate, bo.getReceiptDate());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreateDate()), JstAllotEnterOrder::getReceiptCreateDate, bo.getReceiptCreateDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCalloutWarehouse()), JstAllotEnterOrder::getCalloutWarehouse, bo.getCalloutWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getFoldWarehouse()), JstAllotEnterOrder::getFoldWarehouse, bo.getFoldWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreator()), JstAllotEnterOrder::getReceiptCreator, bo.getReceiptCreator());
        lqw.eq(StringUtils.isNotBlank(bo.getProductNumber()), JstAllotEnterOrder::getProductNumber, bo.getProductNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStyleNumber()), JstAllotEnterOrder::getStyleNumber, bo.getStyleNumber());
        lqw.like(StringUtils.isNotBlank(bo.getShopName()), JstAllotEnterOrder::getShopName, bo.getShopName());
        lqw.eq(bo.getQuantity() != null, JstAllotEnterOrder::getQuantity, bo.getQuantity());
        lqw.eq(JstAllotEnterOrder::getDataSign, "0");
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterOrderRemark()), JstAllotEnterOrder::getAllotEnterOrderRemark, bo.getAllotEnterOrderRemark());
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(JstAllotEnterOrder::getNewOrderDate,
                params.get("beginTime"),
                params.get("endTime"));
        }

        // 根据调入单号和物料编码查询（查询金蝶缺少数据），差异数据bo对象不为空且bo参数为假就导出
        if (CollUtil.isNotEmpty(consignmentBusinessDifferenceBo.getOrderMaterialMap()) && !boParams) {
            // 拿有差异的单号和物料编码
            Map<String, List<String>> orderMaterialMap = consignmentBusinessDifferenceBo.getOrderMaterialMap().stream()
                .flatMap(map -> map.entrySet().stream())
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())))
                .entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey,
                    entry -> entry.getValue().stream().flatMap(List::stream).collect(Collectors.toList())));
            for (Map.Entry<String, List<String>> entry : orderMaterialMap.entrySet()) {
                String innerOrderNumber = entry.getKey();
                List<String> jdMaterialCodes = entry.getValue();
                lqw.or(i -> i.eq(JstAllotEnterOrder::getAllotEnterNumber, innerOrderNumber)
                    .in(JstAllotEnterOrder::getJdMaterialCode, jdMaterialCodes));
            }

            // 拿有差异的日期查询
//            if (CollUtil.isNotEmpty(consignmentBusinessDifferenceBo.getJstOrderDateList())) {
//                lqw.and(i -> i.in(JstAllotEnterOrder::getCompareDateToJd, consignmentBusinessDifferenceBo.getJstOrderDateList()));
//            }

        }

        // 解决bug的查询，如果没有差异数据，那就是期望列表没数据，就返回一个假数据，避免查询所有数据
        if (CollUtil.isEmpty(consignmentBusinessDifferenceBo.getOrderMaterialMap()) && !boParams) {
            lqw.eq(JstAllotEnterOrder::getAllotEnterNumber, 0);
        }
        return lqw;
    }

    /**
     * 导出聚水潭-调拨单列表（导出8、调拨-仓库间调拨的差异数据）
     *
     * @param bo
     */
    @Override
    public List<JstAllotEnterOrderVo> queryListTransferBetweenWarehousesBusinessDifference(JstAllotEnterOrderBo bo) {
        // 计算8、调拨-仓库间调拨场景业务差异数据
        ConsignmentBusinessDifferenceBo consignmentBusinessDifferenceBo = this.calculateTransferBetweenWarehousesBusinessDifference();
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = buildQueryWrapperTransferBetweenWarehousesBusinessDifference(bo, consignmentBusinessDifferenceBo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 构建查询包装器（金蝶缺少的数据）
     * 场景分类：8、调拨-仓库间调拨
     *
     * @param bo                              业务对象，包含查询参数
     * @param consignmentBusinessDifferenceBo 计算业务差异bo对象
     * @return LambdaQueryWrapper 查询包装器，用于后续的条件查询
     */
    private LambdaQueryWrapper<JstAllotEnterOrder> buildQueryWrapperTransferBetweenWarehousesBusinessDifference(JstAllotEnterOrderBo bo, ConsignmentBusinessDifferenceBo consignmentBusinessDifferenceBo) {
        // 检测bo的参数
        Boolean boParams = isAnyFieldNonEmpty(bo);
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<JstAllotEnterOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterNumber()), JstAllotEnterOrder::getAllotEnterNumber, bo.getAllotEnterNumber());
        lqw.eq(bo.getAllotOutNumber() != null, JstAllotEnterOrder::getAllotOutNumber, bo.getAllotOutNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getAllotType()), JstAllotEnterOrder::getAllotType, bo.getAllotType());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptDate()), JstAllotEnterOrder::getReceiptDate, bo.getReceiptDate());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreateDate()), JstAllotEnterOrder::getReceiptCreateDate, bo.getReceiptCreateDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCalloutWarehouse()), JstAllotEnterOrder::getCalloutWarehouse, bo.getCalloutWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getFoldWarehouse()), JstAllotEnterOrder::getFoldWarehouse, bo.getFoldWarehouse());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiptCreator()), JstAllotEnterOrder::getReceiptCreator, bo.getReceiptCreator());
        lqw.eq(StringUtils.isNotBlank(bo.getProductNumber()), JstAllotEnterOrder::getProductNumber, bo.getProductNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStyleNumber()), JstAllotEnterOrder::getStyleNumber, bo.getStyleNumber());
        lqw.like(StringUtils.isNotBlank(bo.getShopName()), JstAllotEnterOrder::getShopName, bo.getShopName());
        lqw.eq(bo.getQuantity() != null, JstAllotEnterOrder::getQuantity, bo.getQuantity());
        lqw.eq(JstAllotEnterOrder::getDataSign, "0");
        lqw.eq(StringUtils.isNotBlank(bo.getAllotEnterOrderRemark()), JstAllotEnterOrder::getAllotEnterOrderRemark, bo.getAllotEnterOrderRemark());
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(JstAllotEnterOrder::getNewOrderDate,
                params.get("beginTime"),
                params.get("endTime"));
        }

        // 根据调入单号和物料编码查询（查询金蝶缺少数据），差异数据bo对象不为空且bo参数为假就导出
        if (CollUtil.isNotEmpty(consignmentBusinessDifferenceBo.getOrderMaterialMap()) && !boParams) {
            // 拿有差异的单号和物料编码
            Map<String, List<String>> orderMaterialMap = consignmentBusinessDifferenceBo.getOrderMaterialMap().stream()
                .flatMap(map -> map.entrySet().stream())
                .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())))
                .entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey,
                    entry -> entry.getValue().stream().flatMap(List::stream).collect(Collectors.toList())));
            for (Map.Entry<String, List<String>> entry : orderMaterialMap.entrySet()) {
                String innerOrderNumber = entry.getKey();
                List<String> jdMaterialCodes = entry.getValue();
                lqw.or(i -> i.eq(JstAllotEnterOrder::getAllotEnterNumber, innerOrderNumber)
                    .in(JstAllotEnterOrder::getJdMaterialCode, jdMaterialCodes));
            }

            // 拿有差异的日期查询
//            if (CollUtil.isNotEmpty(consignmentBusinessDifferenceBo.getJstOrderDateList())) {
//                lqw.and(i -> i.in(JstAllotEnterOrder::getCompareDateToJd, consignmentBusinessDifferenceBo.getJstOrderDateList()));
//            }

        }

        // 解决bug的查询，如果没有差异数据，那就是期望列表没数据，就返回一个假数据，避免查询所有数据
        if (CollUtil.isEmpty(consignmentBusinessDifferenceBo.getOrderMaterialMap()) && !boParams) {
            lqw.eq(JstAllotEnterOrder::getCompareDateToJd, 0);
        }
        return lqw;
    }


    /**
     * 判断任意一个参数值是否不为空
     *
     * @param bo 要检查的 JstAllotEnterOrderBo 对象
     * @return 如果任意一个参数值不为空，则返回 true，否则返回 false
     */
    public boolean isAnyFieldNonEmpty(JstAllotEnterOrderBo bo) {
        return bo.getId() != null ||
            StringUtils.isNotBlank(bo.getIds()) ||
            StringUtils.isNotBlank(bo.getAllotEnterNumber()) ||
            bo.getAllotOutNumber() != null ||
            StringUtils.isNotBlank(bo.getAllotType()) ||
            StringUtils.isNotBlank(bo.getReceiptDate()) ||
            StringUtils.isNotBlank(bo.getReceiptCreateDate()) ||
            StringUtils.isNotBlank(bo.getCalloutWarehouse()) ||
            StringUtils.isNotBlank(bo.getFoldWarehouse()) ||
            StringUtils.isNotBlank(bo.getReceiptCreator()) ||
            StringUtils.isNotBlank(bo.getProductNumber()) ||
            StringUtils.isNotBlank(bo.getStyleNumber()) ||
            StringUtils.isNotBlank(bo.getShopName()) ||
            bo.getQuantity() != null ||
            StringUtils.isNotBlank(bo.getAllotEnterOrderRemark()) ||
            bo.getNewOrderDate() != null ||
            StringUtils.isNotBlank(bo.getJdMaterialCode()) ||
            StringUtils.isNotBlank(bo.getCompareDateToJd());
    }





}
